<template>
  <el-dialog
      v-model="dialogVisible"
      title="采购项填写"
      width="600px"
      :before-close="handleClose"
      class="PurchaseItem"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="PurchaseItem-form">
      <el-form-item label="价格模式">
        <el-radio-group v-model="priceMode" class="PurchaseItem-form-mode-group">
          <el-radio-button label="unit">按单价</el-radio-button>
          <el-radio-button label="total">按总价</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品编码">
        <el-input :model-value="viewProduct?.code || '-'" class="PurchaseItem-form-input" disabled/>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input :model-value="viewProduct?.name || '-'" class="PurchaseItem-form-input" disabled/>
      </el-form-item>
      <el-form-item label="单位">
        <el-input :model-value="viewProduct?.unit || '-'" class="PurchaseItem-form-input" disabled/>
      </el-form-item>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="数量" prop="quantity">
            <el-input-number v-model="form.quantity" :min="0.01" :step="1" :precision="2"
                             class="PurchaseItem-form-number"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="priceMode === 'unit'" label="单价(¥)" prop="unitPrice">
            <el-input-number v-model="form.unitPrice" :min="0" :step="1" :precision="2"
                             class="PurchaseItem-form-number"/>
          </el-form-item>
          <el-form-item v-else label="总价(¥)" prop="totalPrice">
            <el-input-number v-model="form.totalPrice" :min="0" :step="1" :precision="2"
                             class="PurchaseItem-form-number"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item v-if="priceMode === 'unit'" label="小计(¥)">
        <el-input :model-value="formatMoney(totalPrice)" class="PurchaseItem-form-input" disabled/>
      </el-form-item>
      <el-form-item v-else label="单价(¥)">
        <el-input :model-value="formatMoney(form.unitPrice)" class="PurchaseItem-form-input" disabled/>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="PurchaseItem-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, reactive, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {getProduct} from '../../../api/productApi.js'

const props = defineProps({
  visible: {type: Boolean, default: false},
  productId: {type: Number, default: null},
  product: {type: Object, default: null},
  initial: {type: Object, default: null},
  mode: {type: String, required: true}
})
const emits = defineEmits(['update:visible', 'confirm'])

const dialogVisible = ref(false)
const formRef = ref()
const form = reactive({
  quantity: 1,
  unitPrice: 0,
  totalPrice: 0
})
// 独立保存的单价（用于模式切换时还原）
const savedUnitPrice = ref(0)

const priceMode = ref('unit') // 'unit' | 'total'
// 初始化阶段标记，避免初始化设置 priceMode 触发重置逻辑
const initializing = ref(false)

const rules = reactive({
  quantity: [{required: true, message: '请输入数量', trigger: 'change'}],
  unitPrice: [{
    required: true,
    validator: (_r, _v, cb) => {
      if (priceMode.value !== 'unit') return cb()
      const v = Number(form.unitPrice)
      if (!v || v <= 0) return cb(new Error('请输入大于 0 的单价'))
      cb()
    },
    trigger: 'change'
  }],
  totalPrice: [{
    required: true,
    validator: (_r, _v, cb) => {
      if (priceMode.value !== 'total') return cb()
      const v = Number(form.totalPrice)
      if (!v || v <= 0) return cb(new Error('请输入大于 0 的总价'))
      cb()
    },
    trigger: 'change'
  }]
})

const productDetail = ref(null)
const viewProduct = computed(() => props.product || productDetail.value)

watch(() => props.visible, async (v) => {
  dialogVisible.value = v
  if (v) await init()
})
watch(dialogVisible, v => {
  if (!v) emits('update:visible', false)
})

const round2 = (n) => {
  const num = Number(n || 0)
  return Math.round(num * 100) / 100
}

const init = async () => {
  initializing.value = true
  // 商品
  if (props.product && props.product.id) {
    productDetail.value = null
  } else if (props.productId) {
    try {
      productDetail.value = await getProduct(props.productId)
    } catch (e) {
      ElMessage.error('获取商品详情失败')
      productDetail.value = null
    }
  } else {
    productDetail.value = null
  }
  // 初始数量与价格
  if (props.initial) {
    form.quantity = Number(props.initial.quantity || 1)
    form.unitPrice = round2(props.initial.unitPrice)
    form.totalPrice = round2(props.initial.totalPrice != null ? props.initial.totalPrice : form.quantity * form.unitPrice)
  } else {
    form.quantity = 1
    const p = props.product && props.product.id ? props.product : productDetail.value
    if (props.mode === 'purchase') {
      form.unitPrice = p && p.purchasePrice != null ? round2(p.purchasePrice) : 0
    } else if (props.mode === 'sale') {
      form.unitPrice = p && p.salePrice != null ? round2(p.salePrice) : 0
    } else {
      form.unitPrice = 0
    }
    form.totalPrice = round2(form.quantity * form.unitPrice)
  }
  // 初始化独立单价
  savedUnitPrice.value = round2(form.unitPrice)
  // 回显价格模式（若编辑时带入），默认按单价
  priceMode.value = (props.initial && props.initial.priceMode) ? props.initial.priceMode : 'unit'
  initializing.value = false
}

// 联动：数量变化
watch(() => form.quantity, (q) => {
  const qty = Number(q || 0)
  if (priceMode.value === 'unit') {
    form.totalPrice = round2(qty * Number(form.unitPrice || 0))
  } else {
    form.unitPrice = qty > 0 ? round2(Number(form.totalPrice || 0) / qty) : 0
  }
})
// 联动：单价变化（单价模式）
watch(() => form.unitPrice, (p) => {
  if (priceMode.value === 'unit') {
    form.totalPrice = round2(Number(form.quantity || 0) * Number(p || 0))
  }
})
// 联动：总价变化（总价模式）
watch(() => form.totalPrice, (t) => {
  if (priceMode.value === 'total') {
    const qty = Number(form.quantity || 0)
    form.unitPrice = qty > 0 ? round2(Number(t || 0) / qty) : 0
  }
})
// 切换模式时：总价模式置 0，单价模式恢复独立单价，并推导只读字段
watch(priceMode, (m) => {
  if (initializing.value) return
  const qty = Number(form.quantity || 0)
  if (m === 'unit') {
    form.unitPrice = round2(savedUnitPrice.value)
    form.totalPrice = round2(qty * Number(form.unitPrice || 0))
  } else {
    form.totalPrice = 0
    form.unitPrice = qty > 0 ? round2(Number(form.totalPrice || 0) / qty) : 0
  }
})

const totalPrice = computed(() => round2(Number(form.quantity || 0) * Number(form.unitPrice || 0)))

const handleClose = () => {
  dialogVisible.value = false
}

const handleConfirm = async () => {
  try {
    await formRef.value?.validate()
    const p = viewProduct.value || {}
    emits('confirm', {
      productId: p.id,
      code: p.code,
      name: p.name,
      unit: p.unit,
      quantity: Number(form.quantity || 0),
      unitPrice: Number(form.unitPrice || 0),
      totalPrice: Number(priceMode.value === 'unit' ? totalPrice.value : form.totalPrice || 0),
      priceMode: priceMode.value
    })
  } catch (e) {
    // ignore
  }
}

const formatMoney = (v) => Number(v || 0).toFixed(2)
</script>

<style scoped lang="scss">
.PurchaseItem {
  &-form {
    padding: 16px 0;

    &-input {
      width: 100%;
    }

    &-number {
      width: 100%;
    }
  }

  &-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }
}
</style>
